home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 6_3.lha / 6_3 / 6_3d.c < prev    next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  63 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. / assign a string to a substring, version 2
  6. / handling mismatches in lengths
  7. include <memory.h>
  8. include <string.h>
  9.  
  10. / assign a character string to a substring
  11. ubstring& substring::operator=(char *cp)
  12.  
  13.    // disconnect string
  14.    if (str->p->n > 1)
  15. {
  16. str->p->n--;
  17. struct srep *oldp = str->p;
  18. str->p = new struct srep;
  19. str->p->s = new char[strlen(oldp->s) + 1];
  20. strcpy(str->p->s, oldp->s);
  21. str->p->n = 1;
  22. s = str->p->s + (s - oldp->s);
  23. }
  24.  
  25.    int stlen = strlen(cp);
  26.  
  27.    // same size, simply copy data
  28.    if (len == stlen)
  29. {
  30. if (len > 0)
  31.     memcpy(s, cp, len);
  32. }
  33.  
  34.    // expand or shrink data area
  35.    else
  36. {
  37. // allocate the new data segment
  38. char *sps = str->p->s;
  39. const int s1len = s - sps;
  40. const int s3len = strlen(sps) - len - s1len;
  41. char *newdata =
  42.     new char[s1len + stlen + s3len + 1];
  43.  
  44. // copy in the data
  45. if (s1len > 0)
  46.     memcpy(newdata, sps, s1len);
  47. if (stlen > 0)
  48.     memcpy(newdata + s1len, cp, stlen);
  49. if (s3len > 0)
  50.     memcpy(newdata + s1len + stlen,
  51.     s + len, s3len);
  52. newdata[s1len + stlen + s3len]= '\0';
  53.  
  54. // replace pointers
  55. delete str->p->s;
  56. str->p->s = newdata;
  57. s = newdata + s1len;
  58. len = stlen;
  59. }
  60.  
  61.    return *this;
  62.  
  63.